package com.cn.server.tcp;

import com.cn.common.core.model.*;
import com.cn.common.core.serial.Serializer;
import com.cn.common.core.session.Session;
import com.cn.server.msg.MessageHandler;
import com.cn.server.msg.PacketReceiver;
import com.cn.server.websocket.WebSocketMessageDispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class MessageDispatcher implements PacketReceiver {

    public static final int POLICY_REJECT = 2;
    public static final int POLICY_LOG = 1;
    public static final int POLICY_IGNORE = 0;
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketMessageDispatcher.class);
    private final Map<Short, Map<Short, MessageHandler>> handlers = new HashMap<>();
    private final int unsupportedPolicy;

    public MessageDispatcher() {
        unsupportedPolicy = POLICY_REJECT;
    }

    public MessageDispatcher(int unsupportedPolicy) {
        this.unsupportedPolicy = unsupportedPolicy;
    }

    public void register(Short module, Short cmd, MessageHandler handler) {
        Map<Short, MessageHandler> cmdMap = handlers.get(module);
        if (cmdMap == null) {
            cmdMap = new HashMap<>();
            handlers.put(module, cmdMap);
        }
        cmdMap.put(cmd, handler);
    }

    public MessageHandler unRegister(Short module, Short cmd) {
        Map<Short, MessageHandler> cmdMap = handlers.get(module);
        if (cmd == null) {
            return null;
        }
        return cmdMap.remove(cmd);
    }

    @Override
    public void onReceive(Request packet, Session session) {
        LOGGER.debug("onReceive={}", packet);
        Map<Short, MessageHandler> cmdMap = handlers.get(packet.getModule());
        if (cmdMap == null) {
            LOGGER.error("no register module = {}", packet.getModule());
            return;
        }
        LOGGER.debug("当前type" + session.getType());
        Response response = new Response(packet);
        MessageHandler handler = cmdMap.get(packet.getCmd());
        if (handler != null) {
            Result<?> result = handler.handle(packet, session);
            //聊天每个消息都会返回对应的状态，比如发送成功或是失败等等
//                if (packet.getModule() == ModuleId.CHAT) {
//                    //聊天层数据在业务层已经发送
//                    return;
//                }
            //回写数据
            Object object = result.getContent();
            if (object != null) {
                if (object instanceof Serializer) {
                    Serializer content = (Serializer) object;
                    response.setData(content.getBytes());
                }
            }
            response.setStateCode(result.getResultCode());
            session.write(response);
            LOGGER.debug("响应信息,原因:{},状态码:{}", result.getReason(), result.getResultCode());
        }
    }
}
